import 'dart:io';
import 'package:path/path.dart' as path;

class RestartUtil {
  static Future<void> restartApp() async {
    if (Platform.isWindows) {
      try {
        final executablePath = Platform.resolvedExecutable;
        final arguments = Platform.executableArguments;
        final workingDirectory = Directory.current.path;

        print('重启应用 ---> 可执行文件路径: $executablePath');
        print('重启应用 ---> 参数: $arguments');
        print('重启应用 ---> 工作目录: $workingDirectory');

        // 使用 path.join 确保跨平台兼容的路径拼接
        final scriptFilePath = path.join(workingDirectory, 'restart_app.bat');
        final scriptFile = File(scriptFilePath);

        // 对 executablePath 和 arguments 进行转义，防止注入
        final escapedExecutablePath = '"$executablePath"';
        final escapedArguments = arguments.map((arg) => '"$arg"').join(' ');

        // 修复脚本内容，使用字符串拼接确保格式正确
        final scriptContent =
            '@echo off\n'
            'chcp 65001 >nul \n'
            'taskkill /F /IM flutter_deer.exe >nul 2>&1 \n'
            'ping 127.0.0.1 -n 1 >nul \n'
            'cd /d "$workingDirectory"\n'
            'start "" $escapedExecutablePath $escapedArguments \n'
            'ping 127.0.0.1 -n 1 >nul \n'
            'echo "%~f0" \n'
            'del "%~f0" \n'
            'exit \n'
            // 'if exist "%~f0" ( \n'
            // '    del "%~f0" \n'
            // '    echo delete success \n'
            // ') else ( \n'
            // '    echo has not file \n'
            // ') \n'
        ;


        print('重启应用 ---> 脚本内容: $scriptContent');

        await scriptFile.writeAsString(scriptContent);

        // 启动脚本
        await Process.start(
          'cmd.exe',
          // ['/c', 'start', '/b', scriptFile.path],
          ['/c', scriptFile.path],
          mode: ProcessStartMode.detached,
        );
      } catch (e, stackTrace) {
        print('重启应用失败: $e');
        print(stackTrace);
        exit(1); // 使用非0退出码表示异常退出
      }
    } else {
      print('当前平台不支持自动重启');
      exit(0);
    }
  }
}
